# -*- coding:utf-8 -*-
import cgi
import json
import datetime
from flask import render_template, redirect, request, url_for, flash, jsonify, current_app, g
from flask_login import login_required
from sqlalchemy.sql import or_

from app import db
from app.models.risk_manage import Risk_Flow, Risk_Application as RA, RiskPicture, Risk_Loan_Track as RLT
from app.models.account import Staff
from app.views.risk.loan_track import loan_track as main
from app.tools.timestamp import timestamp
from app.tools.message import message
from app.tools.log import log
from app.tools.permission import permission
from app.tools.redis_op import Operator
from .. import *

op = Operator()


def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


main.before_request(signin_required)


@main.before_request
@login_required
@permission(['service', 'director', 'manage', 'finance', 'review', 'admin', 'super'])
def check_permission():
    g.kw = {}
    return


def save_pictures(flow_id, pledge_type, pics):
    flow = u'track_contract'
    domain = current_app.config['QINIU_DOMAIN']
    for pic_name in pics:
        url = domain + pic_name
        form = dict(
            pledge_type=pledge_type,
            flow_id=flow_id,
            url=url,
            flow=flow,
            picture_type='0'  # 跟进图片只有一种，合同,代码已写死
        )
        rp = RiskPicture(**form)
        rp.save()


def has_picture(form, pledge_type):  # 判断有没有图片
    try:
        track_pic_list = json.loads(form.get('track', ''))
    except ValueError:
        return False
    if len(track_pic_list) == 0:
        return False
    return track_pic_list


def divide_term(rlts_list, terms):
    l = []
    for i in range(int(terms)):
        a = i + 1
        l1 = []
        for rlt in rlts_list:
            if str(rlt.times) == str(a):
                l1.append(rlt)
        l.append(l1)
    return l


def update_xfrs():
    import uuid
    xfrs = str(uuid.uuid4())
    op.hset('xfrs', xfrs, 0)
    return xfrs


def calculate_term():
    for ra in RA.query.filter(RA.loan_status.in_((u'即将到期', u'生效'))).all():
        f = '%Y/%m/%d %H:%M:%S'
        dt = datetime.datetime.strptime(ra.deadline, f)
        now = datetime.datetime.now()
        a = dt - now
        total_term = int(ra.days) / 30  # 总共期数， 例如90天应分为3期，total_term=3
        if not total_term:  # 如果是1天、10天略过，因为发起的时候期数已经是1
            continue
        now_term = total_term - a.days / 30
        if not now_term:
            continue
        ra.pay_off_term = now_term
        db.session.add(ra)
    db.session.commit()


@main.route('/index')
def index():
    for ra in RA.query.filter(RA.loan_status.in_((u'即将到期', u'生效'))).all():
        if datetime.datetime.strptime(ra.deadline, "%Y/%m/%d %H:%M:%S") < datetime.datetime.now():
            ra.loan_status = u'逾期'
        elif datetime.datetime.strptime(ra.deadline, "%Y/%m/%d %H:%M:%S") < (
            datetime.datetime.now() - datetime.timedelta(days=5)):
            ra.loan_status = u'即将到期'
    db.session.commit()
    calculate_term()
    return render_template('risk/loan_track/index.html')


@main.route('/get_list', methods=['GET'])
def get_list():
    values = request.values
    limit = int(values.get('limit', '10'))
    offset = int(values.get('offset', '0'))
    list_type = request.values.get('list_type')
    number = values.get('number')
    start = values.get('start')
    end = values.get('end')
    submitter = values.get('submitter')
    area = values.get('area')
    search_type = values.get('search_type')
    tb_name = values.get('tb_name')  # 前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
    try:
        f = '%Y/%m/%d'
        end = datetime.datetime.strptime(end, f)
        dt = end + datetime.timedelta(days=1)  # 需要加一天才可以搜索到原本的end指定的日期
        end = dt.strftime(f)
    except ValueError:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    result = RA.query
    date = {
        'to_launch': RA.timestamp_pass_loan,
        'active': RA.deadline,
        'expired': RA.deadline,
        'pay_off': RA.pay_off_time
    }
    loan_statu = {
        'to_launch': u'待发起',
        # 'active': u'生效',
        'expired': u'逾期',
        'pay_off': u'已还清'
    }
    if tb_name == list_type and search_type != '5':  # 5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
        if search_type == '0':
            g.kw['flow_id'] = number
        if search_type == '1' or search_type == '4':
            g.kw['person_type'] = submitter
        if search_type == '2' or search_type == '4':
            result = result.filter(RA.area.like('%' + area + '%'))
        if search_type == '3' or search_type == '4':
            result = result.filter(date[list_type].between(start, end))

    g.kw['initiator'] = session['staff_number']  # 只能看到自己发起的

    # if list_type == 'to_launch':
    #     g.kw['loan_status'] = u'待发起'
    #     result = result.filter_by(**g.kw)
    #     s = result.order_by(date[list_type])
    # elif list_type == 'active':
    #     g.kw['loan_status'] = u'生效'
    #     result = result.filter_by(**g.kw)
    #     s = result.order_by(RA.deadline)
    # elif list_type == 'expired':
    #     g.kw['loan_status'] = u'逾期'
    #     result = result.filter_by(**g.kw)
    #     s = result.order_by(RA.deadline)
    # elif list_type == 'pay_off':
    #     g.kw['loan_status'] = u'已还清'
    #     result = result.filter_by(**g.kw)
    #     s = result.order_by(RA.pay_off_time)
    if list_type not in ('to_launch', 'active', 'expired', 'pay_off'):
        return jsonify({'state': 1, 'msg': u'参数错误'})
    if list_type == 'active':
        result = result.filter(or_(RA.loan_status == u'生效', RA.loan_status == u'即将到期'))
    else:
        g.kw['loan_status'] = loan_statu[list_type]
    result = result.filter_by(**g.kw)

    s = result.order_by(date[list_type])
    s = s.paginate(offset / limit + 1, limit, False)

    result = s.items
    count = s.total

    data = []
    for item in result:
        date_description = {
            'to_launch': item.timestamp_pass_loan,
            'active': item.deadline,
            'expired': item.deadline,
            'pay_off': item.pay_off_time
        }
        data.append({
            'id': item.id,
            'flow_id': item.flow_id,
            'pledge_type': item.pledge_type,
            'amount': item.amount,
            'days': item.days,
            'area': item.area,
            'name': item.name + '(' + item.person_type + ')',
            'track_number': item.track_number,
            'loan_status': item.loan_status,
            'date_description': date_description[list_type],
            'term': '{}/{}'.format(str(item.pay_off_term) if item.pay_off_term and int(item.pay_off_term) > 0 else '1',
                                   str(int(item.days) / 30) if int(item.days) / 30 else '1'),
            'operate': '',
        })
    json = {'total': count, 'rows': data}
    return jsonify(json)


@main.route('/launch/<flow_id>', methods=['GET'])  # 发起跟进
@permission(['service', 'director', 'admin', 'super'])
def launch(flow_id):
    role = session['role']
    xfrs = update_xfrs()
    ra = RA.query.filter_by(flow_id=flow_id).first()
    if not ra:
        return render_template('404.html'), 404
    if ra.review_status != role and ra.flow_status != u'待发起跟进':
        return render_template('403.html'), 403
    if ra.initiator != session['staff_number']:
        return render_template('403.html'), 403

    return render_template('risk/loan_track/launch.html',
                           role=role,
                           xfrs=xfrs,
                           flow_id=flow_id,
                           ra=ra)


@main.route('/p_launch', methods=['POST'])
def p_launch():
    form = request.form
    xfrs = form.get('xfrs', '')
    pledge_type = form.get('pledge_type', '')
    flow_id = form.get('flow_id')
    if session['role'] not in ('service', 'admin', 'director'):
        return jsonify(dict(
            success=False,
            message=u'不是客服或管理员，不能发起申请'
        ))
    pics = has_picture(form, pledge_type)
    if not pics:
        return jsonify(dict(
            success=False,
            message=u'图片上传不全'
        ))
    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        ra = RA.query.filter_by(flow_id=flow_id).first()
        # staff_number = session['staff_number']
        # ra.track_number = staff_number

        ra.loan_status = u'生效'
        if ra.days == '1':
            ra.loan_status = u'即将到期'
        ra.flow_status = u'跟进中'
        ra.review_status = u'跟进中'
        ra.pay_off_term = u'1'  # 发起贷款之后为第一期。对第N期添加跟进记录 期数取自这里

        # 处理图片
        save_pictures(flow_id, pledge_type, pics)

        ra.save()
        log(u'发起跟进：{}'.format(flow_id))
        return jsonify(dict(
            success=True,
            message=u'跟进发起成功！',
            next=url_for('.index')
        ))
    return jsonify(dict(
        success=False,
        message=u'操作失败！'
    ))


@main.route('/record/<flow_id>', methods=['GET'])
def track(flow_id):
    xfrs = update_xfrs()
    ra = RA.query.filter_by(flow_id=flow_id).first()
    rlts = RLT.query.filter_by(flow_id=flow_id).order_by(RLT.timestamp.desc()).all()
    terms = ra.pay_off_term  # 得到当前期数
    l = divide_term(rlts, terms)  # 按期划分
    s = Staff.query.filter_by(staff_number=ra.track_number).first()
    track_name = s.name
    return render_template('risk/loan_track/track.html',
                           xfrs=xfrs,
                           flow_id=flow_id,
                           ra=ra,
                           track_name=track_name,
                           l=l,
                           len=len,
                           rlts=rlts)


@main.route('/record/add', methods=['POST'])
def add_track():
    form = request.form
    xfrs = form.get('xfrs', '')
    flow_id = form.get('flow_id')
    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        content = form.get('content', '')
        ra = RA.query.filter_by(flow_id=flow_id).first()
        rlt = RLT(form)
        rlt.set_term(ra.pay_off_term)  # 该流程所在还款期数
        rlt.save()
        log(cgi.escape(u'对{}添加跟进记录：{}'.format(flow_id, content)))
        flash(u'添加记录成功！')
        return redirect(url_for('.track', flow_id=flow_id))
    flash(u'添加记录失败！')
    return redirect(url_for('.track', flow_id=flow_id))


@main.route('/pay_off', methods=['POST'])
def pay_off():
    form = request.get_json()
    xfrs = form.get('xfrs', '')
    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        flow_id = form.get('flow_id', '')

        ra = RA.query.filter_by(flow_id=flow_id).first()
        ra.loan_status = u'已还清'
        ra.flow_status = u'完结'
        ra.review_status = u'完结'
        ra.pay_off_time = timestamp()  # 完全还清时间
        now_term = ra.pay_off_term
        track = RLT.query.filter_by(flow_id=flow_id, times=now_term).count()
        if not track:
            return jsonify(dict(
                success=False,
                message=u'本期还没添加任何跟进'
            ))
        ra.save()
        log(u'流水号{}已完全还清放款'.format(flow_id))
        return jsonify(dict(
            success=True,
            message=u'还清操作执行成功'
        ))
    return jsonify(dict(
        success=True,
        message=u'操作失败'
    ))
